package com.zhang.hadoop.netty.netty.protocoltcp;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.springframework.data.crossstore.ChangeSet;

import java.nio.charset.Charset;
import java.util.UUID;

/**
 * @author: zhang yufei
 * @createTime:2022/3/6 10:42
 * @description:
 */
public class MyServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MessageProtocol messageProtocol) throws Exception {
        //接收到数据,并处理
        int length=messageProtocol.getLen();
        byte[] content = messageProtocol.getContent();
        System.out.println("服务器接收到的信息如下");
        System.out.println("长度="+length);
        System.out.println("内容="+new String(content, Charset.forName("utf-8")));
        System.out.println("服务器接收到消息包数量="+ (++this.count));
        //回复消息
        String responseContent= UUID.randomUUID().toString();
        byte[] responseContent2 = responseContent.getBytes("utf-8");
        int responseLen= responseContent2.length;
        //构建一个协议包
        MessageProtocol messageProtocolResponse=new MessageProtocol();
        messageProtocolResponse.setLen(responseLen);
        messageProtocolResponse.setContent(responseContent2);
        channelHandlerContext.writeAndFlush(messageProtocolResponse);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
       cause.printStackTrace();
       ctx.close();
    }


}
